<?php
namespace app\appclass\model;
use app\BaseModel;
use app\card\model\Company;
use app\card\model\UserPhone;
use app\shop\controller\IndexUser;
use app\shop\model\AdminCompany;
use app\shop\model\IndexUserInfo;
use think\facade\Db;



class CardUser extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_appclass_card_user';


    protected $append = [

        'store_name'

    ];


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 13:51
     * @功能说明:门店名称
     */
    public function getStoreNameAttr($value,$data){

        if(!empty($data['store_id'])){

            $store_model = new Company();

            return $store_model->where(['id'=>$data['store_id']])->value('name');
        }

    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-18 15:45
     * @功能说明:会员卡名称
     */
    public function getCardNameAttr($value,$data){

        if(!empty($data['card_id'])){

            $card_model = new CardList();

            return $card_model->where(['id'=>$data['card_id']])->value('title');
        }


    }
    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:00
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $res = $this->insert($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:03
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:04
     * @功能说明:详情
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 13:42
     * @功能说明:统计销售金额
     */
    public function getPrice($dis,$where = [],$status=[]){

        if(empty($status)){

            $data = $this->where($dis)->where($where)->sum('pay_price');

        }else{

            $data = $this->where($dis)->where($where)->where('status','in',$status)->sum('pay_price');
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 13:42
     * @功能说明:统计销售金额
     */
    public function getSaleCount($dis,$where = [],$status=[]){

        if(empty($status)){

            $data = $this->where($dis)->where($where)->count();

        }else{

            $data = $this->where($dis)->where($where)->where('status','in',$status)->count();
        }

        return $data;

    }

    /**
     * @author chenniang
     * @DataTime: 2021-06-15 16:17
     * @功能说明:获取销售或者退款的
     */
    public function getSaleOrCancel($dis,$where = [],$is_cancel=0,$type=0){
        //有没有退款过
        $dis['is_cancel'] = $is_cancel;

        if(empty($type)){

            $data = $this->where($dis)->where($where)->sum('pay_price');

            $data = round($data,2);

        }else{

            $data = $this->where($dis)->where($where)->count();
        }

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-25 16:02
     * @功能说明:
     */
    public function saleOrCancelPrice($dis,$where = []){

        $dis['is_cancel'] = 1;

        $data = $this->where($dis)->where($where)->column('id');

        $log_model = new CardLog();

        $price = $log_model->where('card_user_id','in',$data)->sum('cancel_price');

        return round($price,2);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-25 16:48
     * @功能说明:月退款
     */
    public function monthCancelPrice($dis,$type='',$time = 'month',$where = []){

        $dis['is_cancel'] = 1;

        if(is_numeric($type)){

            $dis['card_type'] = $type;
        }


        if(empty($where)){

            $data = $this->where($dis)->whereTime('create_time',$time)->column('id');

        }else{

            $data = $this->where($dis)->where($where)->column('id');
        }

        $log_model = new CardLog();

        $price = $log_model->where('card_user_id','in',$data)->sum('cancel_price');

        return round($price,2);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-05-20 13:53
     * @功能说明:统计销售金额
     */
    public function getCount($dis,$where=[],$status=[]){

        if(empty($status)){

            $data = $this->where($dis)->where($where)->count();

        }else{

            $data = $this->where($dis)->where($where)->where('status','in',$status)->count();
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-28 15:41
     * @功能说明:获取销售数量或者张数
     */
    public function getSaleCountOrPrice($dis,$where=[],$week='month',$type=0,$card_type=''){

        if(is_numeric($card_type)){

            $dis['card_type'] = $card_type;
        }
        //张数
        if($type==1){

            $dis['is_cancel'] = 0;

            if(!empty($where)){

                $data = $this->where($dis)->where($where)->count();

            }else{

                $data = $this->where($dis)->whereTime('create_time',$week)->count();
            }


        }else{
        //金额
            if(!empty($where)){

                $data = $this->where($dis)->where($where)->sum('pay_price');;

            }else{

                $data = $this->where($dis)->whereTime('create_time',$week)->sum('pay_price');;
            }

            $cancel = $this->monthCancelPrice($dis,$card_type,$week,$where);

            $data   = round($data-$cancel,2);

        }

        return $data;


    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 14:04
     * @功能说明:今日访客
     */
    public function toDayUser($uniacid){

        $user_model = new \app\shop\model\IndexUser();

        $dis = [

            'uniacid' => $uniacid
        ];

        $user_num = $user_model->where($dis)->whereTime('create_time','today')->column('id');

        $card_num = $this->where($dis)->where('user_id','in',$user_num)->group('user_id')->count();

        $count = count($user_num)-$card_num;

        return $count>0?$count:0;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:05
     * @功能说明:
     */
    public function dataList($dis,$page=10,$where=[]){

        $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id','left')
                ->join('longbing_card_appclass_card_list c','a.card_id = c.id')
                ->where($dis)
                ->where(function ($query) use ($where){
                    $query->whereOr($where);
                })
                ->field('a.*,ifnull(b.nickName,a.user_name) as nickName')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();
        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 11:21
     * @功能说明:绑定会员
     */
    public function bindUser($data,$controller=0){

        $card_model = new CardList();

        $card = $card_model->dataInfo(['id'=>$data['card_id']]);

        $data['discount'] = !empty($data['discount'])?$data['discount']:0;

        $end_time = $card['type']==0?$card['time_limit']*86400+$data['open_time']+$data['discount']*86400:$card['time_limit']*86400+$data['open_time'];

        $status = 2;

        if($data['open_time']>time()){

            $status = 1;
        }


        if($end_time<time()){

            $status = 3;
        }

        $insert = [

            'uniacid'   => $data['uniacid'],

            'user_id'   => $data['user_id'],

            'code'      => longbingorderCode(),

            'pay_type'  => $data['pay_type'],

            'card_type' => $card['type'],

            'pay_price' => $data['pay_price'],

            'card_id'   => $card['id'],

            'value'     => $card['value'],

            'discount'  => $data['discount'],

            'true_value'=> $card['value']+$data['discount'],

            'open_time' => $data['open_time'],

            'adviser'   => $data['adviser'],

            'text'      => $data['text'],

            'store_id'  => $card['store_id'],

            'mobile'    => $data['mobile'],

            'end_time'  => $end_time,

            'status'    => $status,

            'effect'    => $card['effect']

        ];


        $res = $this->dataAdd($insert);

        $id  = $this->getLastInsID();
        //添加发卡记录
        $this->controlCard($id,1,$data['uniacid'],$controller,0);

        if($status==2){
            //添加开卡记录
            $this->controlCard($id,2,$data['uniacid'],$controller,0,0,0,$data['open_time']);

        }

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-28 11:06
     * @功能说明:初始化所有未认证的卡
     */
    public function initCardUserAll($uniacid){


        $dis = [

            'uniacid' => $uniacid,

            'user_id' => 0
        ];

        $list = $this->where($dis)->where($dis)->select()->toArray();

        if(!empty($list)){

            $phone_model = new UserPhone();

            $user_model  = new \app\shop\model\IndexUser();

            foreach ($list as $value){

                $dis = [

                    'uniacid' => $uniacid,

                    'phone'   => $value['mobile']
                ];

                $phone = $phone_model->where($dis)->find();

                if(!empty($phone)&&!empty($value['mobile'])){

                    $user_name = $user_model->where(['id'=>$phone['user_id']])->value('nickname');

                    $this->dataUpdate(['id'=>$value['id']],['user_id'=>$phone['user_id'],'user_name'=>$user_name]);

                }

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-01 17:30
     * @功能说明:初始化未认证的会员卡
     */
    public function initCardUser($user_id){

        $phone_model = new UserPhone();

        $phone = $phone_model->where(['user_id'=>$user_id])->value('phone');

        if(!empty($phone)){

            $this->dataUpdate(['user_id'=>0,'mobile'=>$phone],['user_id'=>$user_id]);
        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 14:54
     * @功能说明:操作会员卡
     */
    public function controlCard($card_id,$status,$uniacid,$user_id=0,$update_card = 1,$cancel_price=0,$cancel_type=0,$open_time=0){

        $log_model = new CardLog();
        //是否需要更新会员卡
        if($update_card==1){
            //开卡除外
            $update = [

                'status' => $status
            ];

            if($status==5){
                //退款
                $update['is_cancel'] = 1;
            }

            $res = $this->dataUpdate(['id'=>$card_id],$update);
        }
        //添加操作日志
        $res = $log_model->dataAdd($uniacid,$card_id,$status,$user_id,$cancel_price,$cancel_type,$open_time);

        Db::commit();

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-04 14:04
     * @功能说明:退卡金额
     *
     * 1:未开卡，2:正常，3：已过期，4:已经停卡,5:已退卡
     */
    public function cancelPrice($dis,$time){

        $dis['b.status'] = 5;

        $price = $this->alias('a')
                ->join('longbing_card_appclass_card_user_log b','a.id = b.card_user_id')
                ->where($dis)
                ->whereTime('a.create_time',$time)
                ->group('a.id')
                ->sum('b.cancel_price');

        return $price;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-07 16:05
     * @功能说明:30天内未上课会员
     */
    public function noClassMember($store_id,$type=0){

        $record_model = new ClassRecord();

        $dis = [

            'store_id' => $store_id
        ];

        //30天内上过课的人
        $user_id = $record_model->where($dis)->where('status','in',[1,3])->where('start_time','>',time()-86400*30)->group('user_id')->column('user_id');

//        $user_id[] = 0;

        if($type==0){

            $dis['is_cancel'] = 0;
            //30天内没上过课并且开卡超过30天
            $data = $this->where($dis)->where('open_time','<',time()-86400*30)->where('user_id','not in',$user_id)->group('user_id')->count();

        }else{

            $dis = [

                'a.store_id' => $store_id
            ];

            $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id','left')
                ->join('longbing_card_appclass_class_record c','c.user_id = a.user_id AND c.status = 3','left')
                ->where($dis)
                ->where('a.user_id','not in',$user_id)
                ->where('a.is_cancel','=',0)
                ->where('a.open_time','<',time()-86400*30)
                ->field('a.id,b.nickName,b.avatarUrl,a.user_id,ifnull(MAX(c.start_time),MIN(a.open_time))as no_class_time,MAX(c.start_time) as class_time,MIN(a.open_time) as min_open_time')
                ->group('a.user_id')
                ->paginate(10)
                ->toArray();

            if(!empty($data['data'])){

                foreach ($data['data'] as &$v){

                    $v['no_class_time'] = intval((time()-$v['no_class_time'])/86400);

                }

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-08 09:56
     * @功能说明:本月生日的会员
     */
    public function monthBirthday($store_id){

        $dis = [

            'a.store_id' => $store_id,

            'a.is_cancel'=>0

        ];

        $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id')
                ->where($dis)
                ->whereMonth('birthday')
                ->group('b.id')
                ->count();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-08 10:11
     * @功能说明:访客
     */
    public function customer($store_id){

        $company_model = new AdminCompany();

        $user_model    = new IndexUserInfo();

        $store_id_arr  = $company_model->companyLow($store_id);
        //公司部门id合集
        array_unshift($store_id_arr,$store_id);
        //买过的会员
        $member_id = $this->where(['store_id'=>$store_id,'is_cancel'=>0])->group('user_id')->column('user_id');

        $dis[] = ['a.company_id','in',$store_id_arr];

        $dis[] = ['b.uid','not in',$member_id];

        $dis[] = ['c.is_staff','=',0];

        $data = $user_model->alias('a')
                ->join('longbing_card_collection b','a.fans_id = b.to_uid')
                ->join('longbing_card_user c','c.id = b.uid','left')
                ->where($dis)
                ->group('b.uid')
                ->count();

        return $data;
    }

    /**
     * @author chenniang
     * @DataTime: 2021-06-08 10:11
     * @功能说明:访客
     */
    public function customerList($store_id,$page=10,$where=[]){

        $company_model = new AdminCompany();

        $user_model    = new IndexUserInfo();

        $store_id_arr  = $company_model->companyLow($store_id);
        //公司部门id合集
        array_unshift($store_id_arr,$store_id);
        //买过的会员
        $member_id = $this->where(['store_id'=>$store_id,'is_cancel'=>0])->group('user_id')->column('user_id');

        $dis[] = ['a.company_id','in',$store_id_arr];

        $dis[] = ['b.uid','not in',$member_id];

        $dis[] = ['c.is_staff','=',0];

        $data = $user_model->alias('a')
            ->join('longbing_card_collection b','a.fans_id = b.to_uid')
            ->join('longbing_card_user c','c.id = b.uid','left')
            ->where($dis)
            ->where($where)
            ->field('c.nickName,c.avatarUrl,c.uniacid')
            ->group('b.uid')
            ->paginate($page)
            ->toArray();


        return $data;
    }

    /**
     * @author chenniang
     * @DataTime: 2021-06-08 10:11
     * @功能说明:今日新增访客
     */


    public function todayCustomer($store_id){

        $company_model = new AdminCompany();

        $user_model    = new IndexUserInfo();

        $store_id_arr  = $company_model->companyLow($store_id);
        //公司部门id合集
        array_unshift($store_id_arr,$store_id);
        //买过的会员
        $member_id = $this->where(['is_cancel'=>0])->group('user_id')->column('user_id');

        $dis[] = ['a.company_id','in',$store_id_arr];

        $dis[] = ['b.uid','not in',$member_id];

        $dis[] = ['c.is_staff','=',0];

        $data = $user_model->alias('a')
            ->join('longbing_card_collection b','a.fans_id = b.to_uid')
            ->join('longbing_card_user c','c.id = b.uid')
            ->where($dis)
            ->whereTime('c.create_time','today')
            ->group('b.uid')
            ->count();

        return $data;
    }

    /**
     * @author chenniang
     * @DataTime: 2021-06-08 11:04
     * @功能说明:会员列表
     */
    public function memberList($dis,$where,$page=10){

        $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id','left')
                ->join('longbing_card_user_phone c','c.user_id = b.id','left')
                ->where($dis)
                ->where(function ($query) use ($where){
                    $query->whereOr($where);
                })
                ->field("b.nickName,b.avatarUrl,FROM_UNIXTIME(MAX(a.end_time),'%Y-%m-%d %H:%i:%s') as end_time,a.user_id")
                ->group('a.user_id')
                ->paginate($page)
                ->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['nickName'] = !empty($v['user_id'])?$v['nickName']:'未认证';

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-09 10:28
     * @功能说明:
     */
    public function birthdayUser($dis,$page=10){

        $id = $this->birthdayUserId($dis);

        $data = $this->alias('a')
            ->join('longbing_card_user b','a.user_id = b.id')
            ->join('longbing_card_user_phone c','c.user_id = b.id','left')
            ->where($dis)
            ->where('b.id','in',$id)
            ->field(['b.nickName','b.avatarUrl',"FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i:%s') as create_time",'c.phone',"FROM_UNIXTIME(b.birthday,'%Y-%m-%d') as birthday"])
            ->group('a.user_id')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-09 10:28
     * @功能说明:
     */
    public function birthdayUserId($dis){


        $user = $this->alias('a')
            ->join('longbing_card_user b','a.user_id = b.id')
            ->where($dis)
            ->field(['b.id',"FROM_UNIXTIME(b.birthday,'%m') as birthday_m"])
            ->group('a.user_id')
            ->select()
            ->toArray();

       // $user = Db::name('longbing_card_user')->where(['uniacid'=>$uniacid])->where('birthday','<>',0)->field(['id',"FROM_UNIXTIME(birthday,'%m') as birthday_m"])->select();

        $id = [];

        if(!empty($user)){

            foreach ($user as $value){

                $m = date('m',time());

                if($value['birthday_m']==$m){

                    $id[] = $value['id'];
                }

            }
        }


        return $id;

    }

    /**
     * @author chenniang
     * @DataTime: 2021-06-08 13:48
     * @功能说明:月新增会员
     */
    public function monthMemberList($dis,$page=10,$monthTime = 'a.create_time'){

        $data = $this->alias('a')
            ->join('longbing_card_user b','a.user_id = b.id')
            ->join('longbing_card_user_phone c','c.user_id = b.id','left')
            ->where($dis)
            ->whereMonth($monthTime)
            ->field(['a.user_id','b.nickName','b.avatarUrl',"FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i:%s') as create_time",'c.phone',"FROM_UNIXTIME(b.birthday,'%Y-%m-%d') as birthday"])
            ->group('a.user_id')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-08 14:09
     * @功能说明:储值次数不足此时不足的会员卡
     */
    public function notEnough($dis,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_user b','a.user_id = b.id','left')
            ->where($dis)
            ->field("b.nickName,b.avatarUrl,a.create_time,a.card_name,a.true_value,a.card_id,FROM_UNIXTIME(a.end_time,'%Y-%m-%d %H:%i:%s') as end_time,a.card_type,a.open_time")
            ->group('a.id')
            ->paginate($page)
            ->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['open_time_day'] = intval(($v['open_time']-time())/86400);

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-09 14:36
     * @功能说明:初始化过期的会员卡 还有开卡的
     */
    public function initCard($uniacid){

        $map[] = ['uniacid','=',$uniacid];

        $map[] = ['status','=',3];

        $map[] = ['end_time','>',time()];

        $this->where($map)->where('open_time','<',time())->update(['status'=>2]);

        $this->where($map)->where('open_time','>',time())->update(['status'=>1]);

        $log_model = new CardLog();

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['status','in',[1,2]];

        $dis[] = ['end_time','<',time()];
        //修改过期的卡的状态
        $this->dataUpdate($dis,['status'=>3]);
        //给过期的加个状态
        $list = $this->where($dis)->select()->toArray();

        if(!empty($list)){

            foreach ($list as $k=> $value){

                $data[$k]['create_time'] = $value['end_time'];

                $data[$k]['uniacid']     = $value['uniacid'];

                $data[$k]['card_user_id']= $value['id'];

                $data[$k]['status']      = 3;

            }
            //添加操作日志
            $log_model->saveAll($data);
        }

        $where[] = ['uniacid','=',$uniacid];
        //未开卡的
        $where[] = ['status','=',1];

        $where[] = ['open_time','<',time()];

        $list = $this->where($where)->select()->toArray();
        //修改已经开卡的张泰
        $this->dataUpdate($where,['status'=>2]);

        if(!empty($list)){

            foreach ($list as $k=> $value){

                $data[$k]['create_time'] = $value['open_time'];

                $data[$k]['uniacid']     = $value['uniacid'];

                $data[$k]['card_user_id']= $value['id'];

                $data[$k]['status']      = 2;

            }
            //添加操作日志
            $log_model->saveAll($data);
        }

        return true;

    }



}